package org.example.web.service.impl;

import org.example.advice.NotNull;
import org.example.annotation.MyLog;
import org.example.web.domain.Dept;
import org.example.web.domain.DeptLog;
import org.example.web.mapper.DeptLogMapper;
import org.example.web.mapper.DeptMapper;
import org.example.web.mapper.EmpMapper;
import org.example.web.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogMapper deptLogMapper;
    @Override
    public List<Dept> selectAllDept() {
        return deptMapper.selectAllDept();
    }

    @MyLog
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(String id) {
        try {
            deptMapper.deleteById(id);
            empMapper.deleteByDeptId(id);
        }finally {
            DeptLog  deptLog = new DeptLog();
            deptLog.setCreateTime(new Date());
            deptLog.setDescription("删除部门id为"+id);
            deptLogMapper.addDeptLog(deptLog);
        }
    }

    @MyLog
    @Override
    public void insertDept(Dept dept) {
        if(dept.getName()==null ||dept.getName().isEmpty() ){
            throw new NotNull("添加的部门名称不能为空");
        }
        dept.setCreateTime(new Date());
        dept.setUpdateTime(new Date());
        deptMapper.insertDept(dept);
    }

    @Override
    public Dept selectById(String id) {
        return deptMapper.selectById(id);
    }

    @MyLog
    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(new Date());
        deptMapper.updateDept(dept);
    }
}
